package com.companyname.common;

import java.util.List;
import java.util.concurrent.TimeUnit;

import com.gitee.magic.framework.head.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.base.core.context.message.IMessage;
import com.base.core.context.utils.dingtalk.DingTalkService;
import com.base.core.head.ao.MessageSysAO;
import com.gitee.magic.core.utils.StringUtils;
import com.gitee.magic.core.utils.codec.Md5;

/**
 * 
 * @author start
 *
 */
@ConditionalOnProperty(
		prefix = "dingtalk.app",
		value = {"appKey","appSecret","chatId"})
@Service
public class MessageSysService implements IMessage<MessageSysAO> {

	@Value("${dingtalk.app.appKey}")
	private String appKey;
	@Value("${dingtalk.app.appSecret}")
	private String appSecret;
	@Value("${dingtalk.app.chatId}")
	private String chatId;

	@Value("${exception.limit.message:}")
	private List<String> exceptionMessageLimits;

	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	@Override
	public boolean supports(Class<?> clazz) {
		return clazz.equals(MessageSysAO.class);
	}

	@Override
	public void send(MessageSysAO data) {
		if(!StringUtils.isEmpty(data.getContentId())) {
			for(String s:exceptionMessageLimits) {
				if (data.getContent().contains(s)) {
					String key="exceptionlimit:"+Md5.md5(s);
					//当天累计50条消息发送一次
					Long num=redisTemplate.opsForValue().increment(key);
					redisTemplate.expireAt(key,
							TimeUtils.format(TimeUtils.getSysdateTimeEnd(),TimeUtils.YYYYMMDDHHMMSS_F));
					if(num!=null&&num%50!=0) {
						//未达到上限直接返回
						return;
					}
				}
			}
			String key="messagesys:"+data.getContentId();
			if(redisTemplate.hasKey(key)) {
				return;
			}else {
				redisTemplate.opsForValue().set(key, "1", 1, TimeUnit.HOURS);
			}
		}
		DingTalkService dt=new DingTalkService(appKey,appSecret);
		String accessToken=dt.getAccessToken();
		if(StringUtils.isEmpty(data.getContent())) {
			dt.sendText(accessToken, data.getTitle(), chatId);
		}else {
			dt.sendFile(accessToken, data.getTitle(),data.getContent(), chatId);
		}
	}

}
